<template>
  <div v-if="pipeDialogVisible" class="pipe-dialog" v-dialog-drag>
    <!-- 头部 -->
    <div class="dialog-header">
      <span class="dialog-title">管道设计({{ featureData.properties.CODE }})</span>
      <i class="el-icon-close" @click="handleClose"></i>
    </div>
    <div class="dialog-body">
      <div class="pipe-dialog-content">
        <div id="pipe-map">
          <map-toolbar 
            :webmoduleId="63"
            :filter-options="{
              flat: true,
              excludeCommands: ['addRectangle_pipeline', 'addCircle_pipehole', 'addCircle_pipechildpipe']
            }"
            @command="handleCommand"
            key="pipe-tool"
          />
        </div>
        <!-- 可拖动浮层 -->
        <div 
          class="floating-panel" 
          v-dialog-drag="{
            restrict: true,
            initPosition: false,
            parent: '.pipe-dialog-content'
          }"
          v-if="nowCommandType === 'showPanel'"
        >
          <div class="dialog-header">
            <span>{{ panelTitle }}</span>
            <i class="el-icon-close" @click="closePanel"></i>
          </div>
          <div class="panel-content">
            <component :is="currentComponent" 
            :featureData="featureData" 
            :pipeMeterials="pipeMeterials" 
            :colorList="colorList" 
            :nowPipeProperties="nowPipeProperties"
            @confirmGenerate="confirmGenerate"
            @confirmSubpipe="confirmSubpipe"
            @confirmChangeColor="confirmChangeColor"
            @cancelSubpipe="closePanel"
            v-if="currentComponent"></component>
          </div>
        </div>
      </div>
    </div>
    <div class="dialog-footer">
      <el-button size="mini" @click="handleClose">退出管道设计</el-button>
    </div>
  </div>
</template>

<script>
import L from '@/libs/leaflet'
import SuperMap from '@/libs/supermap'
import { get, cloneDeep, isEmpty } from 'lodash'
import { getSysMapInfoApi, getLayerManagerInfoApi } from '@/deps/api'
import { sessionStorage } from '@/deps/utils'
import { mapService, mapObj, featureService, highlightStyle, createLayerManager, highlightManager } from '@/widgets/mapUtils'
import { getPipeMeterialApi, getColorApi, addChildPipeApi, saveChildPipeProlineApi, deleteChildPipeProlineApi, commitToDatasetApi } from '@/deps/apis/pipeApi'
import MapToolbar from './mapTools.vue'

let featuresDatas = []
let messageInstance = null
let pipeMapObj = null
let layerManager = null
let prolineData = null
export default {
  name: 'PipeDialog',
  components: {
    MapToolbar,
    createPipeSection: () => import('./panelComponents/createPipeSection.vue'), // 管道截面
    createchildpipe: () => import('./panelComponents/createchildpipe.vue'), // 布置子管
    changechildpipecolor: () => import('./panelComponents/changechildpipecolor.vue') // 修改子管颜色
  },
  data() {
    return {
      highlightLayer: null,
      pipeDialogVisible: true,
      featureData: null,
      pipeMeterials: [],
      colorList: [],
      panelTitle: '',
      currentComponent: null,
      getLayering: false,
      nowPipeProperties: null, // 当前管孔信息
      nowCommandType: '' // 当前操作类型，用于区分不同的操作
    }
  },
  async created() {
    // 从 sessionStorage 获取 featureData
    const featureData = sessionStorage('pipe_feature')
    if (featureData) {
      this.featureData = cloneDeep(featureData)
    }
    console.error(this.featureData) // 调试用，确保 featureData 正确获取并处理，避免 undefined er
    // 初始化管道材料
    this.pipeMeterials = await getPipeMeterialApi()
    // 初始化颜色列表
    this.colorList = await getColorApi()
    this.$bus.$on('CHANGE_LAYER_INFO', this.getProlineData)
  },
  async mounted() {
    // sysMapInfo = await getSysMapInfoApi({webmoduleId: 63, rootClassType: 2})
    try {
      await new Promise((resolve, reject) => {
        mapService.getMapInfo((serviceResult) => {
          if (serviceResult.error) {
            reject(serviceResult.error)
          } else {
            resolve(serviceResult.result)
            this.$nextTick(() => {
              this.initMap(serviceResult.result)
            })
          }
        })
      })
    } catch (error) {
      console.error('获取地图服务信息失败:', error)
    }
  },
  methods: {
    getProlineData(data) {
      if (data && data.properties.LAYERNAME === 'C_PRO_OPTLINE' && this.pipeDialogVisible) {
        prolineData = data
        if (this.nowCommandType === 'ispipeprolineIng') {
          this.showMessage('请选择管孔', 'warning', true)
          if (this.nowPipeProperties) {
            this.submitProlineData()
          }
        }
      }
    },
    async initMap(mapInfo) {
      // Check if container exists
      if (!document.getElementById('pipe-map')) {
        console.error('Map container not found')
        return
      }

      if (pipeMapObj) {
        pipeMapObj.remove()
      }

      const bounds = L.bounds(
        L.point(0, 0),
        L.point(2000, 2000)
      )

      const crsConfig = L.CRS.NonEarthCRS({
        bounds: bounds,
        origin: L.point(0, 2000)
      })

      pipeMapObj = L.map('pipe-map', {
        crs: crsConfig,
        center: [0, 0],
        zoom: 4,
        zoomControl: false,
        attributionControl: false,
        detectRetina: true,
        maxZoom: 20,
        minZoom: 0,
        doubleClickZoom: false  // 禁用双击放大
      })
      await this.layerOnMapByFeatures(true)
    },
    clearNowHighlightLayer(nowMap = pipeMapObj) {
      console.error('清除高亮') // 调试用，确保方法被调用
      // 清除之前的高亮
      if (this.highlightLayer) {
        nowMap.removeLayer(this.highlightLayer)
        this.nowPipeProperties = null
      }
    },
    highlightLayerAction(feature, nowMap = pipeMapObj) {
      this.clearNowHighlightLayer(nowMap)
      // 创建高亮图层并置顶
      this.highlightLayer = L.geoJSON(feature, {
        style: highlightStyle
      })
      this.highlightLayer.addTo(nowMap)
      this.highlightLayer.bringToFront()  // 确保图层置顶
    },
    async layerOnMapByFeatures(isFirstLoad = false) {
      try {
        this.getLayering = true
        if (!featuresDatas || isEmpty(featuresDatas)) {
          const data = {
            menuid: '680',
            rootClassType: 5
          }
          const res = await getLayerManagerInfoApi(data)
          if (res && Array.isArray(res)) {
            featuresDatas = res.reduce((acc, item) => {
              if (item.child && Array.isArray(item.child)) {
                acc.push(...item.child)
              }
              return acc
            }, [])
          }
        }
        if (!layerManager) {
          layerManager = createLayerManager(pipeMapObj)
        }
        await layerManager.loadMaps(featuresDatas, this.featureData)
        // 计算所有图层的边界并居中显示
        const layers = layerManager.dataFeatureGroup.getLayers()
        if (layers.length > 0) {
          const bounds = L.latLngBounds([])
          layers.forEach(layer => {
            bounds.extend(layer.getBounds())
            const properties = get(layer, 'feature.properties', {})
            layer.on('click', async (e) => {
              L.DomEvent.stopPropagation(e); // 阻止事件冒泡
              L.DomEvent.preventDefault(e); // 阻止默认行为
              const {FEATURENAME} = get(e.target, 'feature.properties', {});
              console.error(FEATURENAME, 'FEATURENAME')
              // 修改子管颜色逻辑
              if (this.panelTitle === '修改子管颜色' && FEATURENAME === '子管') {
                console.error(FEATURENAME, 'FEATURENAME')
                this.highlightLayerAction(e.target.feature)
                this.nowPipeProperties = e.target.feature;
                return
              }
              // 删除逻辑
              if (this.nowCommandType === 'deleteActionIng') {
                this.showConfirm(`确定删除选中的对象？`, () => {
                  const data = {
                    editType: 'delete',
                    jsonString: JSON.stringify({
                      type: 'Feature',
                      datasetname: get(e.target, 'feature.properties.LAYERNAME', ''),
                      username: get(sessionStorage('userData'), 'userName', ''),
                      ids: [get(e.target, 'feature.properties.SMID', '')]
                    })
                  };
                  commitToDatasetApi(data).then(res => {
                    if (!res.success) this.$message.error('删除失败,请重试');
                    this.$message.success('删除成功');
                    this.layerOnMapByFeatures();
                  });
                })
                return;
              }
              if (FEATURENAME === '管孔' && this.panelTitle === '布置子管') {
                this.highlightLayerAction(e.target.feature)
                this.nowPipeProperties = e.target.feature;
                if (this.nowCommandType === 'ispipeprolineIng') {
                  this.showMessage('请选择子管和光缆', 'warning', true);
                }
                return
              }
              if (FEATURENAME === '子管' && this.nowCommandType !== 'showPanel') {
                // 穿缆逻辑
                if (this.nowCommandType === 'ispipeprolineIng') {
                  this.nowPipeProperties = e.target.feature;
                  if (get(this.nowPipeProperties, 'properties.C_PRO_LINE_ID')) {
                    this.nowPipeProperties = null;
                    this.showMessage('当前子管已穿缆,请选择其他子管', 'warning', true);
                    return;
                  }
                  this.highlightLayerAction(e.target.feature)
                  this.showMessage('请选择光缆', 'warning', true);
                  if (prolineData) this.submitProlineData();
                }
                // 删除穿缆逻辑
                if (this.nowCommandType === 'setdeletechildpipeprolineIng') {
                  if (!get(e.target, 'feature.properties.C_PRO_LINE_ID')) return;
                  const data = {
                    userName: get(sessionStorage('userData'), 'userName', ''),
                    baseinfoid: 1,
                    smid: get(e.target, 'feature.properties.SMID', '')
                  };
                  deleteChildPipeProlineApi(data).then(res => {
                    if (!res.success) this.$message.error('删除穿缆失败,请重试');
                    this.$message.success('删除穿缆成功');
                    this.nowCommandType = '';
                    this.layerOnMapByFeatures();
                  });
                }
                // 定位穿缆逻辑
                if (this.nowCommandType === 'showchildpipeprolineIng') {
                  const C_PRO_LINE_ID = get(e.target, 'feature.properties.C_PRO_LINE_ID')
                  if (C_PRO_LINE_ID) {
                    // 根据圆形的范围计算边界
                    const getParams = (attributeFilter) => {
                      const p = {
                        datasetNames: ['capture:C_PRO_OPTLINE'],
                        spatialQueryMode: 'INTERSECT',
                        fromIndex: 0,
                        toIndex: 1000
                      }
                      p.queryParameter = {attributeFilter}
                      var boundsParam = new SuperMap.GetFeaturesBySQLParameters(p)
                      return boundsParam
                    }
                    let linesInfo = await new Promise((resolve) => {
                      featureService.getFeaturesBySQL(getParams(`SMID IN (${C_PRO_LINE_ID})`), (serviceResult) => {
                        resolve(serviceResult.result)
                      })
                    })
                    linesInfo = get(linesInfo, 'features.features[0]', [])
                    this.highlightLayerAction(linesInfo, mapObj)
                    linesInfo.properties.LAYERNAME = 'C_PRO_OPTLINE'
                    linesInfo.properties.FEATURENAME = '光缆'
                    this.$bus.$emit('CHANGE_LAYER_INFO', linesInfo)
                    console.error(linesInfo)
                    return;
                  }
                }
              }
            })
          })
          isFirstLoad && pipeMapObj.fitBounds(bounds)
        } else {
          this.nowCommandType = '';
        }
        this.getLayering = false
      } catch (err) {
        this.getLayering = false
        console.error('获取图层信息失败:', err)
      }
    },
    // 显示消息提示
    showMessage(message, type = 'warning', persistent = false) {
      if (messageInstance) {
        messageInstance.close()
      }
      messageInstance = this.$message({
        message,
        type,
        duration: persistent ? 0 : 3000,
        onClose: () => {
          messageInstance = null
        }
      })
    },
    // 公共的确认框逻辑
    showConfirm(message, callback, catchFun) {
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(callback).catch(() => { catchFun() })
    },
    // 添加状态管理方法
    toggleCommand(commandType, callback) {
      this.clearNowHighlightLayer()
      if (this.nowCommandType === 'showchildpipeprolineIng') {
        this.clearNowHighlightLayer(mapObj)
      }
      if (this.nowCommandType === commandType) {
        this.nowCommandType = ''
        messageInstance && messageInstance.close()
      } else {
        this.nowCommandType = commandType
        callback && callback()
      }
    },
    // 合并handleCommand中的重复逻辑
    handleCommand(command) {
      if (isEmpty(layerManager.dataFeatureGroup.getLayers()) && command !== 'createPipeSection') {
        return this.showMessage('生成规则截面后再执行其他操作')
      }
      if (!isEmpty(layerManager.dataFeatureGroup.getLayers()) && command === 'createPipeSection') {
        return this.showMessage('请先删除管道后再生成')
      }
      const commandHandlers = {
        createPipeSection: () => this.openPanel(command),
        createchildpipe: () => this.openPanel(command),
        changechildpipecolor: () => this.openPanel(command),
        childpipeproline: () => this.toggleCommand('ispipeprolineIng', this.childpipeproline),
        setdeletechildpipeproline: () => this.toggleCommand('setdeletechildpipeprolineIng', () => this.showMessage('点击已穿缆子管删除', 'warning', true)),
        deleteAction: () => this.toggleCommand('deleteActionIng', () => this.showMessage('点击要删除的对象', 'warning', true)),
        showchildpipeproline: () => this.toggleCommand('showchildpipeprolineIng', () => this.showMessage('点击已穿缆子管定位', 'warning', true))
      }
      if (commandHandlers[command]) {
        commandHandlers[command]()
      }
    },
    openPanel(command) {
      const titleMap = {
        createPipeSection: '生成规则截面',
        createchildpipe: '布置子管',
        childpipeproline: '穿缆',
        changechildpipecolor: '修改子管颜色'
      }
      this.nowPipeProperties = null
      if (this.nowCommandType === 'showPanel' && this.panelTitle === titleMap[command]) {
        this.currentComponent = null
        this.nowCommandType = ''
        this.clearNowHighlightLayer()
        return
      }
      messageInstance && messageInstance.close()
      this.currentComponent = command
      this.panelTitle = titleMap[command]
      this.nowCommandType = 'showPanel'
    },
    closePanel() {
      this.clearNowHighlightLayer()
      this.currentComponent = null
      this.nowCommandType = ''
    },
    confirmGenerate(data) {
      console.log('提交表单数据:', data)
      this.layerOnMapByFeatures(true)
      this.closePanel()
    },
    confirmChangeColor(data) {
      console.log('提交表单数据:', data)
      this.nowPipeProperties = null
      this.layerOnMapByFeatures()
    },
    confirmSubpipe({color, num}) {
      if (!this.nowPipeProperties) {
        this.showMessage('请选择管孔')
        return
      }
      const data = {
        userName: get(sessionStorage('userData'), 'userName', ''),
        baseinfoid: 1,
        childpiepnum: num,
        color,
        pipelineid: get(this.featureData, 'properties.SMID', ''),
        pipeholecode: get(this.nowPipeProperties, 'properties.CODE', ''),
        rootid: 163,
        centerx: get(this.nowPipeProperties, 'geometry.coordinates[0][0]', ''),
        centery: get(this.nowPipeProperties, 'geometry.coordinates[0][1]', ''),
        pipeholesmid: get(this.nowPipeProperties, 'properties.SMID', '')
      }
      console.log('当前管道信息:', this.featureData)
      console.log('当前提交信息', data)
      addChildPipeApi(data).then(res => {
        if (!res.success) {
          this.$message.error(res.message || '布置子管失败，请重试！')
          return
        }
        this.nowPipeProperties = null
        this.layerOnMapByFeatures()
      })
    },
    childpipeproline() {
      if (!this.nowPipeProperties || !prolineData) {
        let mes = '请选择子管和光缆'
        if (this.nowPipeProperties) {
          mes = '请选择光缆'
        }
        if (prolineData) {
          mes = '请选择子管'
        }
        this.showMessage(mes, 'warning', true)
        return
      }
      if (this.nowPipeProperties && prolineData) {
        this.submitProlineData()
      }
    },
    submitProlineData(data) {
      messageInstance && messageInstance.close()
      const pipeCode = get(this.nowPipeProperties, 'properties.CODE', '')
      const cableCode = get(prolineData, 'properties.CODE', '')
      // 实现提交穿缆信息的逻辑
      this.showConfirm(`确认将光缆(${cableCode})穿入子管(${pipeCode})吗？`, () => {
        const data = {
          userName: get(sessionStorage('userData'), 'userName', ''),
          baseinfoid: 1,
          prolineid: get(prolineData, 'id', ''),
          smid: get(this.nowPipeProperties, 'properties.SMID', '')
        }
        saveChildPipeProlineApi(data).then(res => {
          if (!res.success) {
            this.$message.error(res.message || '穿缆失败，请重试！')
            return
          }
          this.$message.success('穿缆成功')
          prolineData = null
          this.nowPipeProperties = null
          this.nowCommandType = ''
          messageInstance && messageInstance.close()
          this.layerOnMapByFeatures()
        })
      }, () => {
        this.nowPipeProperties = null
        this.clearNowHighlightLayer()
        this.showMessage('请选择子管', 'warning', true)
      })
    },
    handleClose() {
      this.$emit('closePipeDialog')
      this.pipeDialogVisible = false
    },
    handleConfirm() {
      this.$emit('confirmPipeDesign')
    }
  },
  beforeDestroy() {
    if (this.highlightLayer) {
      pipeMapObj.removeLayer(this.highlightLayer)
      mapObj.removeLayer(this.highlightLayer)
    }
    if (pipeMapObj) {
      pipeMapObj.remove()
      pipeMapObj = null
      layerManager = null
    }
    prolineData = null
    if (messageInstance) {
      messageInstance.close()
      messageInstance = null
    }
  }
}
</script>

<style lang="scss">
@import url('./panelComponents/pipeDialog.scss');
</style>